// pages/shopping/realName/realName.js
var app = getApp();
var util = require("../../../utils/util.js");
var QQMapWX = require('../../../libs/qqmap-wx-jssdk.js');
var MapWXsap = new QQMapWX({
  key: '3VPBZ-KJ5LQ-7Y55U-GZ6HH-BJ2XH-RBB6B' // 必填
});
var address_component= '';
var areaInfo_name= '';
var area_id_Info= '';
var codeInfo='';
var tdsinfo= '';
var flag= false;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    typeList: [],
    typeListI: 0, //证件类型  0 用户认证 1 企业认证 2政事认证
    name: '', //真实姓名
    idcard: '', //身份证号码
    legalperson: '', //法人代表
    licensenum: '', //统一社会信用代码
    company_name: '',//单位名称
    company_address: '',//单位地址
    comidcard:'',//企业身份证号码
    comname:'',//企业名称
    comaddress: '',//企业地址
    contact: '',//联系人
    tellphone: '',//联系电话
    isDisable: true, //按钮状态
    authInfo:{},//认证信息
    sub_loading:false,//提交按钮动画
    sub_txet:'下一步',//提交按钮文字说明
    readOnly:false,
    id_number_formate:'',
    is_load:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that=this;
    that.getAuthType();

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    var that = this;
    that.getAuthInfo();
    var latlength = wx.getStorageSync('lat');
    var tiMore = wx.getStorageSync('tiMore') ? wx.getStorageSync('tiMore') : 1;
    var lnglength = wx.getStorageSync('lng');
    var area_arr_id = wx.getStorageSync('area_id');
    var area_arr_name = wx.getStorageSync('areaInfo_name');
    var is_chan_ge = wx.getStorageSync('is_change');
    if (is_chan_ge) {
      areaInfo_name = area_arr_name;
      area_id_Info= area_arr_id;
    }
    //console.log('???', area_arr_id.length != 0, area_arr_name.length != 0, tiMore >= 3, latlength == '');
    if (area_arr_id.length != 0 && area_arr_name.length != 0 && tiMore >= 3 && latlength == '' && is_chan_ge) {
      areaInfo_name = area_arr_name;
      area_id_Info = area_arr_id;
      //更新地址
      if (wx.getStorageSync('phone')) {
        that.updateTwoAddress(area_arr_name);
      }
      // console.log('结果',areaInfo_name);
      return
    } else {
      if (latlength != '' || tiMore == undefined || tiMore < 3) {
        that.get_location();
      } else if (tiMore >= 3 && !is_chan_ge && latlength == '') {
        wx.navigateTo({
          url: '../../setPosition/setPosition?mytab=true',
        })
      }
    }
    if (tiMore == 1 || tiMore == undefined || tiMore == '') {
      wx.setStorageSync("tiMore", 2);
    } else if (tiMore == 2) {
      wx.setStorageSync("tiMore", 3);
      wx.setStorageSync('is_change', false);
    }
  },

  //是否授权位置
  get_location() {
    var that = this;
    wx.getLocation({
      success: function (res) {
        wx.setStorageSync('lat', res.latitude);
        wx.setStorageSync('lng', res.longitude);
        that.getCityLocation(res.latitude, res.longitude);
        app.showToast('定位中...')
      },
      fail: function (res) {
        const version = wx.getSystemInfoSync().SDKVersion;
        var area_arr_id = wx.getStorageSync('area_id');
        var area_arr_name = wx.getStorageSync('areaInfo_name');

        if (that.compareVersion(version, '2.3.2') < 0) {
          // 如果希望用户在最新版本的客户端上体验您的小程序，可以这样子提示
          wx.showModal({
            title: '提示',
            content: '当前微信版本过低，无法使用部分功能，请升级到最新微信版本后重试。'
          })
          return false;
        }
        app.showModal("", "需要地理位置定位,请先授权", function () {
          wx.openSetting({
            success(res) {
              if (res.authSetting['scope.userLocation'] == true) {
                // that.position();
              }
            }
          })
        }, function () {

        });
      }
    })
  },
  //根据经纬度获取城市信息
  getCityLocation: function (latitude, longitude) {
    var that = this;
    //方法一：通过WebService API 地址逆解析
    // 方法二：通过微信小程序JavaScript SDK 地址逆解析
    MapWXsap.reverseGeocoder({
      location: {
        latitude: latitude,
        longitude: longitude
      },
      success: function (res) {
        // 更新用户地址
        wx.setStorageSync('country', res.result.address_component.nation);
        wx.setStorageSync('province', res.result.address_component.province);
        wx.setStorageSync('city', res.result.address_component.city);
        wx.setStorageSync('area', res.result.address_component.district);
        address_component = res.result.address_component
        that.getCityCode(res.result.address_component.province, res.result.address_component.city, res.result.address_component.district)

      },
      fail: function (res) {
        //console.log(res);
      },
      complete: function (res) { }
    });
  },
  //根据地址查询地区code
  getCityCode: function (province, city, district) {
    var that = this;
    app.ajax({
      url: 'Common/Areas/getAreasCode',
      method: "POST",
      data: {
        province: province,
        city: city,
        area: district
      },
      success: function (res) {
        //console.log(res.data)
        if (res.data.code == 1000) {
          var areaInfos_name = []; //区域名称
          areaInfos_name.push(res.data.data.province_info.area_name);
          areaInfos_name.push(res.data.data.city_info.area_name);
          areaInfos_name.push(res.data.data.area_info.area_name);
          var area_ids_Info = []; //区域id
          area_ids_Info.push(res.data.data.province_info.id);
          area_ids_Info.push(res.data.data.city_info.id);
          area_ids_Info.push(res.data.data.area_info.id);
          wx.setStorage({ key: 'area_id', data: area_ids_Info });
          wx.setStorage({
            key: 'areaInfo_name',
            data: areaInfos_name
          });
          areaInfo_name= areaInfos_name;
          area_id_Info=area_ids_Info;
          codeInfo= res.data.data;
          tdsinfo = res.data.data.tds_info.tds;

          if (wx.getStorageSync('phone')) {
            that.updateAddress(address_component);
          }
        } else {
          app.showToast(res.data.message);
        }
      }
    })
  },
  //更新用户地址
  updateTwoAddress: function (ad_dr) {
    var that = this;
    app.ajax({
      url: 'User/User/editAddress',
      data: {
        country: '中国',
        province: ad_dr[0],
        city: ad_dr[1],
        area: ad_dr[2],
        id: area_id_Info,
        address_is_update: 2
      },
      success: function (res) {
        //console.log('更新用户地址结果', res)
      }
    })
  },
  // 更新用户地址
  updateAddress: function (addr) {
    var that = this;
    app.ajax({
      url: 'User/User/editAddress',
      data: {
        country: addr.nation,
        province: addr.province,
        city: addr.city,
        area: addr.district,
        id: area_id_Info,
        address_is_update: 2
      },
      success: function (res) {
        //console.log('更新用户地址结果', res)
      }
    })
  },
  compareVersion(v1, v2) {
    v1 = v1.split('.')
    v2 = v2.split('.')
    const len = Math.max(v1.length, v2.length)

    while (v1.length < len) {
      v1.push('0')
    }
    while (v2.length < len) {
      v2.push('0')
    }
    for (let i = 0; i < len; i++) {
      const num1 = parseInt(v1[i])
      const num2 = parseInt(v2[i])

      if (num1 > num2) {
        return 1
      } else if (num1 < num2) {
        return -1
      }
    }

    return 0
  },
  //重新调取地址
  changeAdd() {
    var that = this;
    if (wx.getStorageSync('tiMore') >= 3) {
      wx.setStorageSync("tiMore", 1);
      // wx.setStorageSync('is_change', false);
    }
    that.get_location();
    // wx.navigateTo({
    //   url: '../../setPosition/setPosition?mytab=true',
    // })
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() { 

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },


  // 选择证件类型
  bindPickerChange(e) {
    this.setData({
      typeListI: e.detail.value
    })

    if (this.data.typeListI == 0) {
      if (this.data.name != '' && this.data.idcard != '') {
        this.setData({
          isDisable: false
        })
      } else {
        this.setData({
          isDisable: true
        })
      }
    }

    if (this.data.typeListI == 1) {
      if (this.data.legalperson != '' && this.data.licensenum != '' && this.data.comidcard !='' && this.data.comname !='' && this.data.comaddress !='') {
        this.setData({
          isDisable: false
        })
      } else {
        this.setData({
          isDisable: true
        })
      }
    }

    if (this.data.typeListI == 2) {
      if (this.data.company_name != '' && this.data.company_address != '') {
        this.setData({
          isDisable: false
        })
      } else {
        this.setData({
          isDisable: true
        })
      }
    }

  },

  // 绑定输入事件--用户名称
  getname(e) {
    this.setData({
      name: e.detail.value
    })
    if (this.data.typeListI == 0 && this.data.name != '' && this.data.idcard != '') {
      this.setData({
        isDisable: false
      })
    } else {
      this.setData({
        isDisable: true
      })
    }
  },
  // 绑定输入事件身份证号码
  getidcard(e) {
    this.setData({
      idcard: e.detail.value
    })
    if (this.data.typeListI == 0 && this.data.name != '' && this.data.idcard != '') {
      this.setData({
        isDisable: false
      })
    } else {
      this.setData({
        isDisable: true
      })
    }
  },


  //法人输入
  getlegalperson(e) {
    this.setData({
      legalperson: e.detail.value
    })
    this.exptionValues();
  },

  //统一社会信用代码
  getlicensenum(e) {
    this.setData({
      licensenum: e.detail.value
    })
    this.exptionValues();
  },
  //身份证
  getcomidcard(e) {
    this.setData({
      comidcard: e.detail.value
    })
    this.exptionValues();
  },
  //单位名称 
  getcomname(e) {
    this.setData({
      comname: e.detail.value
    })
    this.exptionValues();
  },
  //单位地址
  getcomaddress(e) {
    this.setData({
      comaddress: e.detail.value
    })
    this.exptionValues();
  },
  //12联系人
  getcontact(e) {
    this.setData({
      contact: e.detail.value
    })
    this.exptionValues();
  },

  //12联系方式
  gettellphone(e) {
    this.setData({
      tellphone: e.detail.value
    })
    this.exptionValues();

  },

  //验证是否可以提交（企业认证）
  exptionValues() {
    if (this.data.typeListI == 1 &&
      this.data.legalperson != '' &&
      this.data.licensenum != '' &&
      this.data.contact != '' &&
      this.data.tellphone != '' &&
      this.data.comidcard != '' &&
      this.data.comname != '' &&
      this.data.comaddress != '') {
      this.setData({
        isDisable: false
      })
    } else {
      this.setData({
        isDisable: true
      })
    }

  },

  getcontact22(e) {
    this.setData({
      contact: e.detail.value
    })
    this.exptionValue();
  },
  gettellphone22(e) {
    this.setData({
      tellphone: e.detail.value
    })
    this.exptionValue();
  },

  //单位名称
  getcompanyname(e) {
    this.setData({
      company_name: e.detail.value
    })
    this.exptionValue();
  },
  //单位地址
  getcompanyaddress(e) {
    this.setData({
      company_address: e.detail.value
    })
    this.exptionValue();
  },
  //统一社会信用代码
  getlicensenum(e) {
    this.setData({
      licensenum: e.detail.value
    })
    this.exptionValues();
  },

  //验证是否可以提交(政事认证)
  exptionValue() {
    if (this.data.typeListI == 2 &&
      this.data.company_name != '' &&
      this.data.company_address != '' &&
      this.data.contact != '' &&
      this.data.tellphone != '' &&
      this.data.licensenum != ''
      ) {
      this.setData({
        isDisable: false
      })
    } else {
      this.setData({
        isDisable: true
      })
    }
  },


  // 下一步
  subAuth(e) {
    var that = this;
    if (flag){
      return false;
    }
    if (that.data.isDisable){
      return false;
    }
    var lasts=wx.getStorageSync('lat');
    if (!lasts && area_id_Info.length==0){
      that.changeAdd();
      return false;
    }
    that.setData({
      sub_txet:'正在验证中~~',
      sub_loading:true,
      isDisable:true
    })
    flag= true;
    var typ_es = e.detail.value.types;
    var name = e.detail.value.name;
    var idcard = e.detail.value.idcard;
    var legalperson = e.detail.value.legalperson;
    var licensenum = e.detail.value.licensenum;
    var comidcard = e.detail.value.comidcard;
    var comname = e.detail.value.comname;
    var comaddress = e.detail.value.comaddress;
    var contact = e.detail.value.contact;
    var tellphone = e.detail.value.tellphone;
    var company_name = e.detail.value.company_name;
    var company_address = e.detail.value.company_address;
    // 用户认证
    if (typ_es == 0) {
      if (name == '') {
        app.showToast('请填写真实姓名');
        return false;
      }
      if (idcard == '') {
        app.showToast('请填写身份证号码');
        return false;
      }
      // ajax请求
      app.ajax({
        url: 'User/Realname/step1',
        data: { 'id_number': idcard, "realname": name,"auth_type":1,"auth_client":1},
        success: function (res) {
          that.setData({
            sub_txet: '下一步',
            sub_loading: false,
            //isDisable: false
          })
          //flag= false;
          if (res.data.code == 1000) {
            app.showToast("验证成功!正在跳转至下一步~~");
            setTimeout(function(){
              wx.navigateTo({
                url: '../uploadDocuments/uploadDocuments?types=0'
              })
            },2000)
          }else{
            that.setData({
              isDisable: false
            })
            flag = false;
            app.showToast(res.data.message);
          } 
                             
        }
      })
     
    }

    // 企业认证
    if (typ_es == 1) {
      if (legalperson == '') {
        app.showToast('请填写法人代表');
        return false;
      }
      if (licensenum == '') {
        app.showToast('请填写统一社会信用代码');
        return false;
      }
      if (comidcard == '') {
        app.showToast('请填写身份证号码');
        return false;
      }
      if (comname == '') {
        app.showToast('请填写单位名称');
        return false;
      }
      if (comaddress == '') {
        app.showToast('请填写单位地址');
        return false;
      }
      // ajax请求
      app.ajax({
        url: 'User/Realname/step1',
        data: { 'license_number': licensenum, "legal_person": legalperson,'comidcard':comidcard,'comname':comname,'comaddress':comaddress, "auth_type": 2, 'contact': contact, 'tellphone': tellphone,"auth_client": 1},
        success: function (res) {
          that.setData({
            sub_txet: '下一步',
            sub_loading: false,
          })
          if (res.data.code == 1000) {
            app.showToast("验证成功!正在跳转至下一步~~");
            setTimeout(function () {
              wx.navigateTo({
                url: '../uploadDocuments/uploadDocuments?types=1'
              })
            }, 2000)
          } else {
            that.setData({
              isDisable: false
            })
            flag = false;
            app.showToast(res.data.message);
          }
        
        }
      })

    }


    //政事认证
    if (typ_es == 2) {
      if (company_name == '') {
        app.showToast('请填写单位名称');
        return false;
      }
      if (licensenum == '') {
        app.showToast('请填写统一社会信用代码');
        return false;
      }
      if (company_address == '') {
        app.showToast('请填写单位地址');
        return false;
      }

      // ajax请求
      app.ajax({
        url: 'User/Realname/step1',
        data: { "auth_type": 3, 'user_id': that.data.user_id, 'company_name': company_name, 'company_address': company_address, 'contact': contact, 'tellphone': tellphone, "auth_client": 1, 'license_number': licensenum},
        success: function (res) {
          that.setData({
            sub_txet: '下一步',
            sub_loading: false,      
          })
          if (res.data.code == 1000) {
            app.showToast("验证成功!正在跳转至下一步~~");
            setTimeout(function () {
              wx.navigateTo({
                url: '../uploadDocuments/uploadDocuments?types=2&user_id=' + that.data.user_id
              })
            }, 2000)
          } else {
            that.setData({
              isDisable: false
            })
            flag = false;
            app.showToast(res.data.message);
          }    
                
        }
      })
    }

    
  },
  //获取用户认证信息
  getAuthInfo() {
    var that = this;
    wx.showLoading();
    app.ajax({
      url: "User/Realname/getAuthInfo",
      data: {},
      success: function (res) {
        flag = false;
        wx.hideLoading()
        if (res.data.code == 1000) {
          var isDisable = true;
          if (util.isExitsVariable(res.data.data.realname) && util.isExitsVariable(res.data.data.id_number)){
            isDisable = false;
          }
          //是否可编辑
          var readOnly = false;
          if(res.data.data.status!=-1 && res.data.data.status!=3){
            readOnly = true;
          }
       
          that.setData({
            authInfo: res.data.data,
            name:res.data.data.realname,
            idcard: res.data.data.id_number,
            id_number_formate: res.data.data.id_number,
            isDisable: isDisable,
            readOnly: readOnly,
            typeListI: res.data.data.auth_type == 1 ? 0 : (res.data.data.auth_type ==2?1:2),
            legalperson: res.data.data.realname,
            licensenum: res.data.data.business_license_number,
            comidcard: res.data.data.id_number,
            comname: res.data.data.company_name,
            comaddress: res.data.data.company_address,
            contact: res.data.data.contact,
            tellphone: res.data.data.tellphone,
            company_name: res.data.data.company_name,
            company_address: res.data.data.company_address,

          })
         
        }
        that.setData({
          is_load:true
        })
      }
    })
  },

  //获取认证类型
  getAuthType: function () {
    var that = this;
    app.ajax({
      url: 'Common/Common/getAuthType',
      method: "POST",
      data: { user_id: that.data.user_id },
      success: function (res) {
        if (res.data.code == 1000) {
          that.setData({
            typeList: res.data.data
          })
        }
      }
    })

  }

  


})